﻿using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;
using SmartProduction.Domain.采购委外订单;
using SmartProduction.ErrorCode;
using SmartProduction.Infarstructrue.Interface;
using SmartProduction.Write.API.Application.Commands.SupplierCommand;

namespace SmartProduction.Write.API.Application.CommandHandlers.SupplierCommandHandler
{
    /// <summary>
    /// 供应商添加命令处理
    /// </summary>
    public class SupplierCreateCommandHandler : IRequestHandler<SupplierCreateCommand, APIResult<object>>
    {
        private readonly IMapper mapper;

        /// <summary>
        /// 仓储-供应商
        /// </summary>
        private readonly IBaseRepository<Supplier> supplierRepository;

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="mapper"></param>
        /// <param name="supplierRepository">仓储-供应商</param>
        public SupplierCreateCommandHandler(IMapper mapper, IBaseRepository<Supplier> supplierRepository)
        {
            this.mapper = mapper;
            this.supplierRepository = supplierRepository;
        }

        public async Task<APIResult<object>> Handle(SupplierCreateCommand request, CancellationToken cancellationToken)
        {
            APIResult<object> result = new APIResult<object>();

            string newCode = await GenerateSupplierCodee();
            var info=mapper.Map<Supplier>(request);

            info.SupplierCode = newCode;  // 使用生成的编码
            info.CreatedTime = DateTime.Now;

            var data = supplierRepository.AddAsync(info).Result;
            if (data > 0)
            {
                result.Code = APIEnums.添加成功;
                result.Msg = APIEnums.添加成功.ToString();
                result.data = data;
            }
            else
            {
                result.Code = APIEnums.添加失败;
                result.Msg = APIEnums.添加失败.ToString();
            }
            return await Task.FromResult(result);
        }


        // 编码生成方法（示例格式：PR-20240605-0045）
        private async Task<string> GenerateSupplierCodee()
        {
            // 获取当天最大编码
            DateTime today = DateTime.Today;
            string datePart = today.ToString("yyyyMMdd");
            string prefix = $"PR-{datePart}-";

            var maxCode = await supplierRepository.GetAll().Result
                           .Where(p => p.SupplierCode.StartsWith(prefix))
                           .OrderByDescending(p => p.SupplierCode)
                           .Select(p => p.SupplierCode)
                           .FirstOrDefaultAsync();

            // 解析序列号
            int serialNumber = 1;
            if (!string.IsNullOrEmpty(maxCode))
            {
                string lastNumber = maxCode.Split('-').Last();
                if (int.TryParse(lastNumber, out int lastSerial))
                {
                    serialNumber = lastSerial + 1;
                }
            }

            // 格式化为4位数字
            return $"{prefix}{serialNumber:D4}";
        }
    }
}
